package com.lbd.system.service.impl;


import com.lbd.base.service.BaseServiceImpl;
import com.lbd.system.bean.Employee;
import com.lbd.system.dao.EmployeeRepository;
import com.lbd.system.service.EmployeeService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

/**
 * Created by WangYajie on 2016/9/12.
 */
@Service
@Transactional
public class EmployeeServiceImpl extends BaseServiceImpl<Employee, EmployeeRepository> implements EmployeeService {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    EmployeeRepository employeeRepository;


    @Override
    public Specification<Employee> getSpecification(Employee employee) {
        return null;
    }

    /**
     * 构建查询条件和参数
     *
     * @param employee
     * @param parameter
     * @return
     */
    @Override
    public String buildJpql(Employee employee, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  Employee t   ");
        if (employee != null) {
            if (StringUtils.isNotBlank(employee.getLoginName())) {
                jpqlBuilder.append(" and  loginName like :loginName");
                parameter.put("loginName", employee.getLoginName());
            }
            if (StringUtils.isNotBlank(employee.getTelephone())) {
                jpqlBuilder.append(" and  telephone like :telephone");
                parameter.put("telephone", employee.getTelephone());
            }
        }
        jpqlBuilder.append(" ORDER BY t.createdDate DESC ");
        return jpqlBuilder.toString();
    }

    /**
     * 通过Id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee findById(String id) {
        return employeeRepository.findOne(id);
    }

    /***
     * 用户登录
     *
     * @param employee
     * @return
     */
    @Override
    public Employee login(Employee employee) {
        Employee employeeDB = employeeRepository.findByLoginNameAndPassword(employee.getLoginName(), employee.getPassword());
        if (employeeDB == null) {
            throw new RuntimeException("登录失败,用户名或者密码不存在");
        }
        employeeDB.setLastLoginTime(new Date());
        return employeeDB;
    }


}